package com.czy.owner.ui.packagecardproject;

import android.app.Dialog;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.czy.otherlib.wheelview.adapters.ArrayWheelAdapter;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.adapter.PunchRecordAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.callback.RecyclerHeadersDecoration;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.PunchRecordModel;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.timersection.TimerSectionDialog;
import com.czy.owner.widget.timersection.listener.OnSectionSelListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.data.Type;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;


/**
 * Created by wangyang on 2017/4/19 0019.
 * 划卡记录
 */
public class PunchRecordActivity extends BaseActivity implements OnRefreshListener {
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.refresh_target)
    RecyclerView rvPunchRecord;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    private List<PunchRecordModel> list = new ArrayList<>();
    private int userPackageId;
//    private PunchRecordAdapter mAdapter;
    private TreeMap<String, Integer> groupBillsMap = new TreeMap<>();
    private int currentYear, currentMonth, currentDay;

    private long startTime;
    private long endTime;
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_punch_record;
    }

    @Override
    protected void initInjector() {

    }


    /**为了更新头部临时方案*/
    RecyclerHeadersDecoration headersDecor;
    private void resetAdapter(){
        PunchRecordAdapter mAdapter = new PunchRecordAdapter(PunchRecordActivity.this, list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(PunchRecordActivity.this);
        rvPunchRecord.setLayoutManager(layoutManager);
        rvPunchRecord.setAdapter(mAdapter);
        if(headersDecor != null) {
            rvPunchRecord.removeItemDecoration(headersDecor);//移除之前的旧的Header
        }
        headersDecor = new RecyclerHeadersDecoration(mAdapter);
        rvPunchRecord.addItemDecoration(headersDecor);
    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.punch_record);
        userPackageId = getIntent().getIntExtra("userPackageId", 0);

        rvPunchRecord.addItemDecoration(new RecycleViewDivider(PunchRecordActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        swipeToLoadLayout.setRefreshing(true);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setLoadMoreEnabled(false);

        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR);
        currentMonth = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);
        getDataList();

    }

    @Override
    protected void updateViews() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_punch_record_img_right, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.img_canader:
                showDateDialog();
                break;
        }
        return super.onOptionsItemSelected(item);

    }

    private void getDataList() {
        String url = Constants.APP_API_BASE + Constants.OWN_PAC_USERPACKAGERECORD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PunchRecordActivity.this).getSession());
        params.addBodyParameter("userPackageId", userPackageId + "");
        params.addBodyParameter("startDate", startTime>0?startTime+"":"");
        params.addBodyParameter("endDate", endTime>0?endTime+"":"");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang","划款记录=="+result);
                String data = PhoneUtils.checkResponseFlag(PunchRecordActivity.this, result);
                list.clear();
                groupBillsMap.clear();
                try {
                    if (data != null) {
                        Gson gson = new GsonBuilder().create();
                        list = gson.fromJson(data, new TypeToken<List<PunchRecordModel>>() {
                        }.getType());

                        for (int i = 0; i < list.size(); i++) {
                            String groupName = TimeUtils.formatTimeDifference5(list.get(i).getEndTime());
                            MyLog.e("yang","groupName=="+groupName);
                            //如果Map已经存在以该记录的日期为分组名的分组，则将该条记录插入到该分组中
                            if (groupBillsMap.containsKey(groupName)) {
                                list.get(i).setSort(groupBillsMap.get(groupName));
                                //如果不存在，以该记录的日期作为分组名称创建分组，并将该记录插入到创建的分组中
                            } else {
                                groupBillsMap.put(groupName, i);
                                list.get(i).setSort(Long.valueOf(i));
                                list.get(i).setMyGroupName(groupName);
                            }
                        }

                    }
                    resetAdapter();
//                    mAdapter.setList(list);
                    checkTips();
//                    mAdapter.notifyDataSetChanged();
                } catch (Exception e) {

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                checkTips();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                swipeToLoadLayout.setRefreshing(false);

            }

            @Override
            public void onFinished() {
                swipeToLoadLayout.setRefreshing(false);

            }
        });
    }


    @Override
    public void onRefresh() {
        getDataList();
    }

    private void checkTips() {
        if (list != null && list.size() > 0) {
            tvTip.setVisibility(View.GONE);
        } else {
            tvTip.setVisibility(View.VISIBLE);
        }
    }


    private void showDateDialog(){

        TimerSectionDialog timerSectionDialog = new TimerSectionDialog.Builder()
                .setCallBack(new OnSectionSelListener() {
                    @Override
                    public void onDateSet(TimerSectionDialog timerSectionDialog, long startMillSeconds, long endMillSeconds) {
                        MyLog.e("TimePicker","startMillSeconds = " + startMillSeconds);
                        MyLog.e("TimePicker","endMillSeconds = " + endMillSeconds);
                        startTime = startMillSeconds;
                        endTime = endMillSeconds;
                        getDataList();
                    }
                })
                .setCancelStringId("取消")
                .setSureStringId("确认")
                .setTitleStringId("请选择日期")
                .setCyclic(true)
                .setCurrentStartMillseconds(startTime == 0?System.currentTimeMillis():startTime)
                .setCurrentEndMillseconds(endTime==0?System.currentTimeMillis():endTime)
                .setMaxMillseconds(System.currentTimeMillis())
                .setThemeColor(ContextCompat.getColor(this,R.color.appThemeColor))
                .setType(Type.YEAR_MONTH_DAY)
                //.setWheelItemTextNormalColor(ContextCompat.getColor(mContext,R.color.timetimepicker_default_text_color))
                //.setWheelItemTextSelectorColor(ContextCompat.getColor(mContext,R.color.timepicker_toolbar_bg))
                .setWheelItemTextSize(12)
                .build();

        timerSectionDialog.show(getSupportFragmentManager(), "year_month_day");
    }

    private void showDateDialogUnuse() {
        int yearIndex = 0, monthIndex = currentMonth - 1, dayIndex = currentDay - 1, yearIndex2 = 0, monthIndex2 = currentMonth - 1, dayIndex2 = currentDay - 1;
        Calendar tmpCalendar = Calendar.getInstance();
        Date date = null;
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        final Dialog mDateDialog = new Dialog(PunchRecordActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(PunchRecordActivity.this).inflate(R.layout.dialog_punch_record_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.tv_archive_add_title);
        tvTitle.setText("请选择日期");
        final WheelView wvYear = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year);
        final WheelView wvMonth = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month);
        final WheelView wvDay = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day);

        final WheelView wvYear2 = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year2);
        final WheelView wvMonth2 = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month2);
        final WheelView wvDay2 = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day2);

//开始时间
        final String[] yearArray = new String[20];
        for (int i = currentYear; i > currentYear - 20; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == i) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);
        wvYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(PunchRecordActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        final String[] monthArray = new String[12];
        for (int j = 0; j < 12; j++) {
            monthArray[j] = "" + (j + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == j) {
                monthIndex = j;
            }
        }
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<String>(this, monthArray);
        monthAdapter.setTextSize(20);
        wvMonth.setViewAdapter(monthAdapter);
        wvMonth.setCurrentItem(monthIndex);
        wvMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<>(PunchRecordActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        int dayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[yearIndex].replace("年", "")), monthIndex + 1);
        final String[] dayArray = new String[dayOfMonth];
        for (int k = 0; k < dayOfMonth; k++) {
            dayArray[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(this, dayArray);
        dayAdapter.setTextSize(20);
        wvDay.setViewAdapter(dayAdapter);
        wvDay.setCurrentItem(dayIndex);


//             结束时间


        final String[] yearArray2 = new String[20];
        for (int o = currentYear; o > currentYear - 20; o--) {
            yearArray2[currentYear - o] = "" + o + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == o) {
                yearIndex2 = currentYear - o;
            }
        }
        ArrayWheelAdapter<String> yearAdapter2 = new ArrayWheelAdapter<>(this, yearArray2);
        yearAdapter2.setTextSize(20);
        wvYear2.setViewAdapter(yearAdapter2);
        wvYear2.setCurrentItem(yearIndex2);
        wvYear2.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex2 = wvDay2.getCurrentItem();
                int tmpDayOfMonth2 = getDayOfMonth(Integer.parseInt(yearArray2[wvYear2.getCurrentItem()].replace("年", "")), wvMonth2.getCurrentItem() + 1);
                String[] tmpDayArray2 = new String[tmpDayOfMonth2];
                for (int p = 0; p < tmpDayOfMonth2; p++) {
                    tmpDayArray2[p] = "" + (p + 1) + "日";
                }
                if (tmpIndex2 >= tmpDayOfMonth2) {
                    tmpIndex2 = tmpDayOfMonth2 - 1;
                }
                ArrayWheelAdapter<String> dayAdapter2 = new ArrayWheelAdapter<>(PunchRecordActivity.this, tmpDayArray2);
                dayAdapter2.setTextSize(20);
                wvDay2.setViewAdapter(dayAdapter2);
                wvDay2.setCurrentItem(tmpIndex2);
            }
        });

        final String[] monthArray2 = new String[12];
        for (int q = 0; q < 12; q++) {
            monthArray2[q] = "" + (q + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == q) {
                monthIndex2 = q;
            }
        }
        ArrayWheelAdapter<String> monthAdapter2 = new ArrayWheelAdapter<>(this, monthArray2);
        monthAdapter2.setTextSize(20);
        wvMonth2.setViewAdapter(monthAdapter2);
        wvMonth2.setCurrentItem(monthIndex2);
        wvMonth2.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex2 = wvDay2.getCurrentItem();
                int tmpDayOfMonth2 = getDayOfMonth(Integer.parseInt(yearArray2[wvYear2.getCurrentItem()].replace("年", "")), wvMonth2.getCurrentItem() + 1);
                String[] tmpDayArray2 = new String[tmpDayOfMonth2];
                for (int r = 0; r < tmpDayOfMonth2; r++) {
                    tmpDayArray2[r] = "" + (r + 1) + "日";
                }
                if (tmpIndex2 >= tmpDayOfMonth2) {
                    tmpIndex2 = tmpDayOfMonth2 - 1;
                }
                ArrayWheelAdapter<String> dayAdapter2 = new ArrayWheelAdapter<>(PunchRecordActivity.this, tmpDayArray2);
                dayAdapter2.setTextSize(20);
                wvDay2.setViewAdapter(dayAdapter2);
                wvDay2.setCurrentItem(tmpIndex2);
            }
        });

        int dayOfMonth2 = getDayOfMonth(Integer.parseInt(yearArray2[yearIndex].replace("年", "")), monthIndex2 + 1);
        final String[] dayArray2 = new String[dayOfMonth2];
        for (int k = 0; k < dayOfMonth2; k++) {
            dayArray2[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex2 = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter2 = new ArrayWheelAdapter<String>(this, dayArray2);
        dayAdapter2.setTextSize(20);
        wvDay2.setViewAdapter(dayAdapter2);
        wvDay2.setCurrentItem(dayIndex2);


        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", ""), txtMonth = "0" + (wvMonth.getCurrentItem() + 1), txtDay = "0" + (wvDay.getCurrentItem() + 1);
                txtMonth = txtMonth.substring(txtMonth.length() - 2);
                txtDay = txtDay.substring(txtDay.length() - 2);


                String txtYear2 = yearArray2[wvYear2.getCurrentItem()].replace("年", ""), txtMonth2 = "0" + (wvMonth2.getCurrentItem() + 1), txtDay2 = "0" + (wvDay2.getCurrentItem() + 1);
                txtMonth2 = txtMonth2.substring(txtMonth2.length() - 2);
                txtDay2 = txtDay2.substring(txtDay2.length() - 2);

                // MyLog.e("yang", "开始时间==" + txtYear + "-" + txtMonth + "-" + txtDay + "结束时间==" + txtYear2 + "-" + txtMonth2 + "-" + txtDay2);
//
                long startTime = TimeUtils.getTimeStamp(txtYear + "年" + txtMonth + "月" + txtDay + "日" + "00时00分00秒", "yyyy年MM月dd日HH时mm分ss秒");
                long endTime = TimeUtils.getTimeStamp(txtYear2 + "年" + txtMonth2 + "月" + txtDay2 + "日" + "23时59分59秒", "yyyy年MM月dd日HH时mm分ss秒");

                if (endTime >= startTime) {
                    getDataList();
                    mDateDialog.dismiss();
                } else {
                    PhoneUtils.ShowToastMessage(PunchRecordActivity.this, "开始时间不能大于结束时间");
                }

            }
        });


        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });


        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }


    private int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }


}
